
/**
 * Copyright 2009 cestum.org
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
 
package org.waveprotocol.wave.model.id {
import org.goverla.collections.ArrayList;
import org.goverla.collections.ListCollectionViewIterator;


/**
 * A filter which accepts a set of wavelets ids.
 *
 */
public final class IdFilter {
	
	private static var NO_WAVELET_IDS:ArrayList= new ArrayList();
	private static var NONE_PREFIX:ArrayList= new ArrayList();
	
	/** An id filter which accepts all ids. */
	public static var ALL_IDS:IdFilter= new IdFilter(NO_WAVELET_IDS, NONE_PREFIX);
	
	private var ids:ArrayList;
	private var prefixes:ArrayList;
	
	/**
	 * Creates a new filter from a collection of ids and a collection of
	 * id prefixes. Either parameter may be empty but neither parameter
	 * may be null.
	 *
	 * Prefixes must be non-empty strings.
	 *
	 * @param ids ids to match exactly
	 * @param prefixes id prefixes to match
	 */
	public function IdFilter(ids:ArrayList, prefixes:ArrayList) {
		this.ids = ids;
		this.prefixes = prefixes;
		if (prefixes.contains("")) {
			throw new Error("Empty id prefix");
		}
	}
	
	/**
	 * Gets an unmodifiable view of the ids in the filter.
	 */
	public function getIds():ArrayList {
		return this.ids;
	}
	
	/**
	 * Gets an unmodifiable view of the id prefixes in the filter.
	 */
	public function getPrefixes():ArrayList {
		return this.prefixes;
	}
	
	/**
	 * Checks whether an id is accepted by the filter.
	 */
	public function accepts(id:WaveletId):Boolean {
		var match:Boolean= ids.length == 0 && prefixes.length == 0;
		if (!match) {
			match = ids.contains(id);
		}
		var itr:ListCollectionViewIterator= prefixes.createIterator();
		while (itr.hasNext() && !match) {
			var temp:String= String(itr.next());
			match = match || id.getId().indexOf(temp) == 0;
		}
		return match;
	}
}
}